package com.menghao.sso.client.filter;


import com.menghao.sso.client.util.CommonUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>对TGT和ST有无校验.<br>
 *
 * @author menghao.
 * @version 2017/11/15.
 */
public class AuthenticationFilter extends AbstractCasFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        Cookie cookie = WebUtils.getCookie(request, CommonUtils.TGT_ID);
        // 无TGT，说明未登录
        if (null == cookie || cookie.getValue() == null) {
            String originalRequest = makeOriginalRequest(request, response);
            // 没有ticket则重定向登录
            String loginUrl = makeLoginRequest(originalRequest);
            response.sendRedirect(loginUrl);
            return;
        }
        // 有TGT，无ST，说明已登录但登录其他系统
        String serviceTicket = request.getParameter(CommonUtils.ST_ID);
        if (!StringUtils.hasText(serviceTicket)) {
            String originalRequest = makeOriginalRequest(request, response);
            String validateRequest = makeValidateTGTRequest(originalRequest, cookie.getValue());
            response.sendRedirect(validateRequest);
            return;
        }
        // 具备TGT和ST
        filterChain.doFilter(request, response);
    }

}
